package de.hhbk.feedbackmodul.daobeans;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import de.hhbk.feedbackmodul.daointerfaces.UserDaoIF;
import de.hhbk.feedbackmodul.entities.User;

@Stateless
public class UserDaoBean implements UserDaoIF {

	@PersistenceContext(unitName = "FeedbackModulEJB")
	private EntityManager manager;
	
	private Logger logger = Logger.getLogger(this.getClass());

	@SuppressWarnings("unchecked")
	@Override
	public List<User> getAllUsers() throws Exception {
		try
		{
			Query query = manager.createQuery("SELECT u FROM User u", User.class);
			return (List<User>)query.getResultList();
		}
		catch(Exception e)
		{
			logger.error("Error while reading Users: "+e.getMessage(), e);
			throw e;
		}
	}

	@Override
	public void createUser(User user) throws Exception {
		try
		{
			manager.persist(user);
		}
		catch(Exception e)
		{
			logger.error("Error while persisting User: "+e.getMessage(), e);
			throw e;
		}
	}

	@Override
	public void updateUser(User user) throws Exception {
		try
		{
			manager.merge(user);
		}
		catch(Exception e)
		{
			logger.error("Error while updating User: "+e.getMessage(), e);
			throw e;
		}
	}

	@Override
	public void deleteUser(User user) throws Exception {
		try
		{
			User userToDelete = manager.find(User.class, user.getId());
			manager.remove(userToDelete);
		}
		catch(Exception e)
		{
			logger.error("Error while deleting User: "+e.getMessage(), e);
			throw e;
		}
	}
}
